#include "IOUnit.h"
#include <cstdio>
#include <vector>


IOUnit::IOUnit()
{
	bitCount = 0;
	nextChar = '\0';
	pIbuf = NULL;
	pObuf = NULL;
	bitArray = NULL;
	//activate fail-bit for exceptions
	pIFile.exceptions(std::ifstream::failbit);
}


IOUnit::~IOUnit()
{

}


bool IOUnit::checkFile(char* filename)
{
	bool fileOk = true;

	try
	{
		pIFile.open(filename, std::ifstream::in);
		pIFile.close();
	}
	catch (std::ifstream::failure &e)
	{
		std::cerr << "Could not open file: " << filename << '\n';
		fileOk = false;
	}
	return fileOk;
}


std::vector<short>* IOUnit::readFromFile(char* filename, int offset, bool binary)
{


	pIFile.open(filename,std::ifstream::in|std::ios::binary);


	pIbuf = pIFile.rdbuf();
	pIbuf->pubseekpos(offset);

	//as long as there is data
	do{

		//get the next 8 bit from the streambuffer
		nextChar = pIbuf->sgetc();

		//read the next 8 Bits from ch into the bitVector
		for(int i = 0; i< 8; i++)
		{
			/*AND-Operation of nextChar AND 10000000(bin). So we check the first (HSB) if it is 1.
			After that we shift the result 7 bits to the right. If the HSB is 1 the bitVector will push_back a 1*/
			bitVector.push_back((nextChar & 0x80) >> 7);
			bitCount++;
			//Shift the char-Bits one bit to the left, so that we can check the second, third.... bit in the second, third,... loop run.
			nextChar <<= 1;
		}

	}while(pIbuf->snextc() != EOF);


	std::cout << "##### File \"" << filename << "\" got " << bitCount << " Bits for testing. #####\n";
	
	pIFile.close();

	return &bitVector;
}



void IOUnit::writeToFile(char* filename, char* data, int size, bool binary)
{
	pOFile.open(filename, std::ofstream::out);

	pOFile.write(data, size);

	pObuf = pOFile.rdbuf();

	pOFile.close();

}
